<template>
  <div class="system-settings">
    <div class="page-header">
      <div class="header-left">
        <h3>系统设置</h3>
        <p>管理系统全局配置和监控设置</p>
      </div>
      <div class="header-right">
        <el-button type="primary" :loading="saving" @click="saveAllSettings">
          {{ saving ? '保存中...' : '保存所有设置' }}
        </el-button>
      </div>
    </div>

    <div class="settings-content">
      <!-- 随机休眠配置 -->
      <el-card title="随机休眠配置" class="setting-card">
        <template #header>
          <div class="card-header">
            <span>随机休眠配置</span>
            <el-switch v-model="sleepConfig.enabled" />
          </div>
        </template>

        <el-form label-width="140px">
          <el-form-item label="最小休眠时间">
            <el-input-number
              v-model="sleepConfig.min_seconds"
              :min="1"
              :max="3600"
              :disabled="!sleepConfig.enabled"
              style="width: 200px" />
            <span class="unit">秒</span>
          </el-form-item>

          <el-form-item label="最大休眠时间">
            <el-input-number
              v-model="sleepConfig.max_seconds"
              :min="sleepConfig.min_seconds || 1"
              :max="3600"
              :disabled="!sleepConfig.enabled"
              style="width: 200px" />
            <span class="unit">秒</span>
          </el-form-item>

          <el-form-item label="">
            <div class="help-text">
              随机休眠功能可以让交易脚本在执行间隔中随机等待，避免被检测为机器行为
            </div>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 交易监控配置 -->
      <el-card title="交易监控配置" class="setting-card">
        <template #header>
          <div class="card-header">
            <span>交易监控配置</span>
            <el-switch v-model="monitorConfig.enabled" />
          </div>
        </template>

        <el-form label-width="140px">
          <el-form-item label="滑点告警阈值">
            <el-input-number
              v-model="monitorConfig.slippage_threshold"
              :precision="4"
              :step="0.0001"
              :min="0.0001"
              :max="0.01"
              :disabled="!monitorConfig.enabled"
              style="width: 200px" />
            <span class="unit">% (万分之{{ Math.round(monitorConfig.slippage_threshold * 10000) }})</span>
          </el-form-item>

          <el-form-item label="">
            <div class="help-text">
              当交易的滑点率超过设定阈值时，系统将自动发送告警并暂停相关账号的交易脚本
            </div>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 异常通知配置 -->
      <el-card title="异常通知配置" class="setting-card">
        <template #header>
          <div class="card-header">
            <span>异常通知配置</span>
            <el-switch v-model="notificationConfig.enabled" />
          </div>
        </template>

        <el-form label-width="140px">
          <el-form-item label="企业微信地址">
            <el-input
              v-model="notificationConfig.webhook_url"
              placeholder="请输入企业微信Bot的Webhook地址"
              :disabled="!notificationConfig.enabled"
              clearable />
          </el-form-item>

          <el-form-item label="">
            <div class="action-buttons">
              <el-button
                type="primary"
                :disabled="!notificationConfig.enabled || !notificationConfig.webhook_url"
                :loading="testingNotification"
                @click="testNotification">
                {{ testingNotification ? '测试中...' : '测试通知' }}
              </el-button>
            </div>
            <div class="help-text">
              配置企业微信机器人地址，用于接收交易异常告警通知
            </div>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 监控状态概览 -->
      <el-card title="监控状态" class="setting-card">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ monitorStats.todayTransactions }}</div>
              <div class="stat-label">今日交易数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ monitorStats.abnormalTransactions }}</div>
              <div class="stat-label">异常交易数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ monitorStats.averageSlippage }}%</div>
              <div class="stat-label">平均滑点率</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ monitorStats.alertCount }}</div>
              <div class="stat-label">告警次数</div>
            </div>
          </el-col>
        </el-row>

        <div class="stats-actions">
          <el-button @click="refreshStats">刷新统计</el-button>
          <el-button type="primary" @click="viewAbnormalTransactions">查看异常交易</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { http } from '@/utils/request'

const router = useRouter()

// 状态管理
const saving = ref(false)
const testingNotification = ref(false)
const loading = ref(false)

// 配置数据
const sleepConfig = reactive({
  enabled: true,
  min_seconds: 30,
  max_seconds: 120
})

const monitorConfig = reactive({
  enabled: true,
  slippage_threshold: 0.0003
})

const notificationConfig = reactive({
  enabled: true,
  webhook_url: ''
})

const monitorStats = reactive({
  todayTransactions: 0,
  abnormalTransactions: 0,
  averageSlippage: 0,
  alertCount: 0
})

// 初始化
onMounted(async () => {
  await loadSettings()
  await loadMonitorStats()
})

// 加载所有设置
const loadSettings = async () => {
  loading.value = true
  try {
    // 加载随机休眠配置
    const sleepResponse = await http.get('/system/settings/random-sleep')
    Object.assign(sleepConfig, sleepResponse.data)

    // 加载监控配置
    const monitorResponse = await http.get('/system/settings/monitor')
    Object.assign(monitorConfig, monitorResponse.data)

    // 加载通知配置
    const notificationResponse = await http.get('/system/settings/notification')
    Object.assign(notificationConfig, notificationResponse.data)

  } catch (error) {
    ElMessage.error('加载设置失败')
    console.error('加载设置失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载监控统计
const loadMonitorStats = async () => {
  try {
    const response = await http.get('/monitor/stats')
    Object.assign(monitorStats, response.data)
  } catch (error) {
    console.error('加载监控统计失败:', error)
  }
}

// 保存所有设置
const saveAllSettings = async () => {
  saving.value = true
  try {
    // 保存随机休眠配置
    await http.put('/system/settings/random_sleep_config', {
      settingValue: sleepConfig,
      description: '随机休眠时间配置'
    })

    // 保存监控配置
    await http.put('/system/settings/monitor_config', {
      settingValue: monitorConfig,
      description: '交易监控配置'
    })

    // 保存通知配置
    await http.put('/system/settings/notification_config', {
      settingValue: notificationConfig,
      description: '异常通知配置'
    })

    ElMessage.success('所有设置保存成功')

  } catch (error) {
    ElMessage.error('保存设置失败')
    console.error('保存设置失败:', error)
  } finally {
    saving.value = false
  }
}

// 测试通知
const testNotification = async () => {
  testingNotification.value = true
  try {
    const response = await http.post('/monitor/test-notification')
    ElMessage.success('测试通知发送成功')
  } catch (error) {
    ElMessage.error('测试通知失败')
    console.error('测试通知失败:', error)
  } finally {
    testingNotification.value = false
  }
}

// 刷新统计
const refreshStats = async () => {
  await loadMonitorStats()
  ElMessage.success('统计数据已刷新')
}

// 查看异常交易
const viewAbnormalTransactions = () => {
  router.push('/monitor/abnormal-transactions')
}
</script>

<style lang="scss" scoped>
.system-settings {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .header-left {
      h3 {
        margin: 0 0 5px;
        color: #303133;
        font-size: 18px;
        font-weight: 600;
      }

      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .settings-content {
    .setting-card {
      margin-bottom: 20px;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: 600;
      }

      .unit {
        margin-left: 8px;
        color: #909399;
        font-size: 14px;
      }

      .help-text {
        font-size: 12px;
        color: #909399;
        line-height: 1.4;
        margin-top: 4px;
      }

      .action-buttons {
        margin-bottom: 8px;
      }

      .stat-item {
        text-align: center;
        padding: 16px;
        background: #f8f9fa;
        border-radius: 6px;

        .stat-value {
          font-size: 24px;
          font-weight: 600;
          color: #303133;
          margin-bottom: 4px;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
        }
      }

      .stats-actions {
        margin-top: 16px;
        text-align: center;

        .el-button {
          margin: 0 8px;
        }
      }
    }
  }
}
</style>